<template>
  <div>
    <Modal v-model="show" width="1000">
      <template #header>
        <!-- 供稿端 直接获取额度
            管理端 当选择录入单位时获取额度
         -->
        <div class="ivu-modal-header-inner">
          稿件上传额度：
          <span class="text-highlight">{{ manuQuota.total || '-' }}篇/日</span>
          &nbsp; 当前单位今日还可上传
          <span class="text-highlight">{{ manuQuota.available || '0' }}篇</span>
        </div>
      </template>

      <Form
        class="custom-ivu-form"
        ref="formRef"
        :label-width="100"
        :model="formData"
        :rules="rules"
        @submit.native.prevent="handleFormSubmit"
      >
        <FormItem label="稿件标题" prop="title">
          <Input v-model="formData.title" placeholder="请输入" size="large" clearable></Input>
        </FormItem>

        <FormItem label="稿件链接" prop="url">
          <Input v-model="formData.url" placeholder="请输入" type="url" size="large" clearable>
            <!-- <Select v-model="selectUrl" slot="prepend" style="width: 100px">
              <Option value="http://">http://</Option>
              <Option value="https://">https://</Option>
            </Select> -->
          </Input>
        </FormItem>

        <FormItem v-if="end === 'manage'" label="代录入单位" prop="organ">
          <Select v-model="formData.organ" class="" clearable>
            <Option v-for="(nt, i) of organList" :key="i" :value="nt.key">{{ nt.value }}</Option>
          </Select>
        </FormItem>

        <FormItem label="所属主题" prop="theme">
          <Select
            v-model="formData.theme"
            placeholder="请选择所属主题(最多可选择5个主题)"
            size="large"
            multiple
            clearable
            @on-change="handleThemeSelectChange"
          >
            <Option v-for="(nt, i) of themeList" :key="i" :value="nt.key" :disabled="nt.disabled">
              {{ nt.value }}
            </Option>
          </Select>
        </FormItem>

        <FormItem label="产品分类" class="form-item--radio" prop="product">
          <RadioGroup v-model="formData.product">
            <Radio v-for="(it, i) of productList" :key="i" :label="it.key">
              <span>{{ it.value }}</span>
            </Radio>
          </RadioGroup>
        </FormItem>

        <FormItem label="领域分类" class="form-item--radio">
          <RadioGroup v-model="formData.field">
            <Radio v-for="(it, i) of fieldList" :key="i" :label="it.key">
              <span>{{ it.value }}</span>
            </Radio>
          </RadioGroup>
        </FormItem>

        <FormItem label="网盘链接">
          <Input v-model="formData.networkUrl" :label-width="60" placeholder="请输入" size="large" clearable></Input>
        </FormItem>

        <FormItem label="提取码" prop="networkCode" :rules="rules_code">
          <Input v-model="formData.networkCode" :label-width="60" placeholder="请输入" size="large" clearable></Input>
        </FormItem>

        <Button class="d-none" type="primary" html-type="submit">查询</Button>
      </Form>

      <template #footer>
        <div class="text-center">
          <Button class="ivu-btn--round" @click="close">取消</Button>
          <Button class="ml14 ivu-btn--round" type="primary" @click="handleFormSubmit">上传</Button>
        </div>
      </template>
    </Modal>

    <ModalConfrim :visible.sync="uploadSuccess" title="上传成功" :show-footer="false">
      <template #header>
        上传成功
        <svg-icon style="width: 24px; height: 24px; vertical-align: bottom" icon-class="icon-success"></svg-icon>
      </template>
      <p class="text-center f14">
        稿件上传成功。
        <a class="a-normalize" @click.prevent="handleUploadAfter(open)">继续上传</a>
        或返回
        <a class="a-normalize" @click.prevent="handleUploadAfter(close)">我的稿件</a>
        页面。
      </p>
    </ModalConfrim>

    <!--  <Icon custom="i-icon i-icon-shop_fill" size="24" /> <Icon type="md-close-circle" /> -->
    <ModalConfrim :visible.sync="uploadFail" title="上传成功" :show-footer="false">
      <template #header>
        上传失败
        <Icon type="md-close-circle" size="24" color="#ed4014" />
      </template>
      <p class="f14">稿件上传失败。稿件正文中可能存在敏感词，请修改后重新上传</p>
    </ModalConfrim>
  </div>
</template>

<script>
import ModalConfrim from '@/components/common/ModalConfrim/ModalConfrim'

import { createRules, createForm } from './service'
import { cloneDeep } from '@/utils/uitls.js'

// request
import { getOrganQuotaById } from '@/api/manageEnd/manuscript/pendingReview'
import { getDailyQuota } from '@/api/provideEnd'

// 主题选择最大数量
const THEME_MAX_NUM = 5

// vuex
import { createNamespacedHelpers } from 'vuex'
const { mapActions } = createNamespacedHelpers('system')
export default {
  name: 'ModalUploadManu',

  components: { ModalConfrim },

  props: {
    visible: { type: Boolean },

    end: { default: '' },
  },

  data: () => ({
    manuQuota: {},

    formData: createForm(),
    rules: createRules(),
    rules_code: createRules().networkCode,

    selectUrl: 'https://',

    uploadSuccess: false,
    uploadFail: false,
  }),

  computed: {
    show: {
      get() {
        return this.visible
      },

      set(v) {
        this.$emit('update:visible', v)
      },
    },
    themeList() {
      const list = this.$store.getters.themeList
      return list.map((it) => ({
        ...it,
        disabled: false,
      }))
    },
    productList() {
      return this.$store.getters.productList
    },
    fieldList() {
      return this.$store.getters.fieldList
    },
    organList() {
      return this.$store.getters.organList
    },
  },

  watch: {
    'formData.networkUrl'(v) {
      if (!v.trim()) {
        if (!this.rules_code.required) return
        this.rules_code = createRules().networkCode
        this.formData.code = ''
        return
      }

      if (this.rules_code.required) return
      const r = createRules().networkCode
      r.required = true
      this.rules_code = r
    },

    'formData.organ'(v) {
      if (!v && v !== 0) return (this.manuQuota = {})
      // console.log(v)
      this.getOrganQuotaById(v)
    },

    visible(v) {
      if (!v) {
        this.resetData()
      } else {
        this.getAllOptions()
      }
    },
  },

  methods: {
    ...mapActions(['getSystemThemeList', 'getProductList', 'getFieldsList', 'getOrganList']),

    resetData() {
      setTimeout(() => {
        this.$refs.formRef.resetFields()
        this.formData = createForm()
      }, 50)
    },

    open() {
      this.show = true
    },
    close() {
      this.show = false
    },

    open_uploadScuuess() {
      this.uploadSuccess = true
    },
    close_uploadScuuess() {
      this.uploadSuccess = false
    },

    open_uploadFailed() {
      this.uploadFail = true
    },
    close_uploadFailed() {
      this.uploadFail = false
    },

    handleThemeSelectChange(v) {
      let cb = null
      if (v.length >= THEME_MAX_NUM) {
        cb = (it) => !v.includes(it.key)
      } else {
        cb = () => false
      }
      this.themeList.forEach((it) => {
        it.disabled = cb(it)
      })
    },

    handleFormSubmit() {
      if (this.manuQuota.available && this.manuQuota.available < 0) {
        this.$Message.error('可上传额度不足')
        return
      }
      // console.log(this.$refs.formRef)
      this.$refs.formRef.validate().then((valid) => {
        if (!valid) return

        const data = cloneDeep(this.formData)
        // data.url = this.selectUrl + data.url
        data.theme = data.theme.join()
        // return
        this.$emit('on-submit', data)
      })

      /* (valid) => {
        if (valid) {
          this.$emit('on-submit', this.formData)
        } else {
          this.$Message.error('Fail!')
          this.uploadFail = true
          setTimeout(() => (this.uploadFail = false), 1200)
        }
      } */
    },

    handleUploadAfter(cb) {
      this.close_uploadScuuess()
      this.resetData()
      cb()
    },

    /* 管理端获取额度 */
    async getOrganQuotaById(id) {
      const res = await getOrganQuotaById(id)
      const data = res.data.data || {}
      this.manuQuota = data
    },

    /* 供稿端获取额度 */
    async getDailyQuota() {
      const res = await getDailyQuota()
      const data = res.data.data || {}
      this.manuQuota = data
    },

    /* 表单选项无数据时。进行请求 */
    getAllOptions() {
      if (!(this.themeList && this.themeList.length)) {
        this.getSystemThemeList()
      }
      if (!(this.productList && this.productList.length)) {
        this.getProductList()
      }
      if (!(this.fieldList && this.fieldList.length)) {
        this.getFieldsList()
      }
      if (!(this.organList && this.organList.length)) {
        this.getOrganList()
      }
    },
  },

  mounted() {
    if (this.end === 'manage') {
    } else {
      this.getDailyQuota()
    }
  },
}
</script>

<style lang="less" scoped>
.custom-ivu-form {
  margin: 10px 20px 0 0;
}
.form-item--radio {
  /deep/ .ivu-radio-wrapper + .ivu-radio-wrapper {
    margin-left: 50px;
  }
}
</style>
